<template>
  <div class="app-container" v-loading.fullscreen.lock="loading">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 选择院系 -->
      <el-form-item label="选择查询" prop="deptId">
        <el-cascader v-model="class_cas" ref="cas" style="width: 500px;" :options="cascaderData"
          :props="{ checkStrictly: true }" @change="handleChange" clearable filterable></el-cascader>
      </el-form-item>
      <!-- 选择学年 -->
      <el-form-item label="选择学年" prop="stuYearId">
        <el-select id="stuYearId" style="width:300px;" v-model="queryParams.stuYearId" placeholder="请选择学年">
          <el-option :key="i" v-for="(v, i) in stu_year_list" :value="v.id" :label="v.stuYearName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" size="mini" @click="exportV = true">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
      <el-table-column label="学年" align="center" prop="stuYearName" width="150" v-if="columns[0].visible" />
      <el-table-column label="学号" align="center" prop="stuNo" width="150" v-if="columns[1].visible" />
      <el-table-column label="班级排名" align="center" prop="classRank" width="80" v-if="columns[2].visible" />
      <el-table-column label="专业排名" align="center" prop="majorRank" width="80" v-if="columns[3].visible" />
      <el-table-column label="学生" align="center" prop="stuName" width="150" v-if="columns[4].visible" />
      <el-table-column label="学生状态" align="center" prop="status" v-if="columns[5].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.srs_stu_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="综合素质总成绩" align="center" prop="score" width="80" v-if="columns[6].visible" />
      <el-table-column label="思想品德" align="center" prop="iamScore" width="80" v-if="columns[7].visible" />
      <el-table-column label="第二课堂换算分" align="center" prop="classtwoScore" width="80" v-if="columns[8].visible" />
      <el-table-column label="综合评价" align="center" prop="ceScore" width="80" v-if="columns[9].visible" />
      <el-table-column label="科学文化平均学分绩" align="center" prop="stuScore" width="80" v-if="columns[10].visible" />
      <el-table-column label="体能素质" align="center" prop="sportScore" width="80" v-if="columns[11].visible" />

      <el-table-column label="班级" align="center" prop="className" width="280" v-if="columns[12].visible" />
      <el-table-column label="院系" align="center" prop="deptName" width="240" v-if="columns[13].visible" />
      <el-table-column label="专业" align="center" prop="majorName" width="240" v-if="columns[14].visible" />
      <!-- <el-table-column label="年级" align="center" prop="gradeName"  width="240"/>
      <el-table-column label="学年" align="center" prop="stuYearName" width="200"/> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      :page-sizes="[5, 10, 30, 50]" @pagination="getList" />
    <!-- charts -->
    <div ref="scoreCharts" style="width: 1500px; height: 800px; margin: 50px auto; margin-bottom: 0;"></div>

    <el-dialog title="选择导出" :visible.sync="exportV" width="600px" append-to-body>
      <el-form label-width="120px">
        <el-form-item label="学年">
          <el-select id="stuYearId" style="width: 400px;" v-model="exportForm.stuYearId" placeholder="请选择学年">
            <el-option :key="i" v-for="(v, i) in stu_year_list" :value="v.id" :label="v.stuYearName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业/班级">
          <el-cascader placeholder="请选择专业或班级" style="width: 400px;" :options="cascaderData"
            :props="{ checkStrictly: true }" @change="exportChange" clearable filterable></el-cascader>
        </el-form-item>
        <el-form-item label="">
          <el-button size="mini" @click="doExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


  </div>
</template>

<script>
import { listCphScore, doExport } from "@/api/stuCQS/info-fill/cqScore";
import * as XLSX from 'xlsx';
import { workbook2blob, openDownloadDialog } from "@/api/helpFunc";
import * as echarts from "echarts";
import { scoreDistribution } from "@/api/stuCQS/statistics";
import { treeStudent } from "@/api/stuCQS/basedata/student";
import { listAllYear as listYear } from "@/api/stuCQS/basedata/year";


export default {
  name: "Statistics",
  dicts: ['srs_stu_status'],
  data() {
    return {
      class_cas: [],
      columns: [
        { key: 0, label: `学年`, visible: true },
        { key: 1, label: `学号`, visible: true },
        { key: 2, label: `班级排名`, visible: true },
        { key: 3, label: `专业排名`, visible: true },
        { key: 4, label: `学生`, visible: true },
        { key: 5, label: `学生状态`, visible: true },
        { key: 6, label: `综合素质总成绩`, visible: true },
        { key: 7, label: `思想品德`, visible: true },
        { key: 8, label: `第二课堂`, visible: true },
        { key: 9, label: `综合评价`, visible: true },
        { key: 10, label: `科学文化平均学分绩`, visible: true },
        { key: 11, label: `体能素质`, visible: true },
        { key: 12, label: `班级`, visible: true },
        { key: 13, label: `院系`, visible: true },
        { key: 14, label: `专业`, visible: true },
      ],

      exportForm: {
        stuYearId: null,
        classId: null,
        majorId: null
      },
      exportV: false,

      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优秀宿舍表格数据
      groupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuYearId: 1,
      },
      // 表单参数
      form: {},
      // 级联数据
      cascaderData: null,
      //学年列表
      stu_year_list: [],
      // 当前分数分布情况
      currentSD: [],
      isDisabled: false
    };
  },
  created() {
    //this.getList();
    this.getCascaderData()
    this.getStuYear()
    //this.getScoreDistribution()

  },
  methods: {
    exportChange(value) {
      this.exportForm = {
        ...this.exportForm,
        majorId: value[1],
        classId: value[2],
      }
    },

    async doExport() {
      this.loading = true;
      let res = await doExport(this.exportForm);
      this.loading = false;
      if (res.code == 200) {
        let data = res.data;
        const header = ['1学年', '2学院', '3专业', '4班级', '5学号', '6姓名', '7思想品德', '8体能素质', '9综合评价', '10科学文化素质', '11第二课堂', '12总成绩', '13班级排名', '14专业排名'];
        const header_zh = {
          '1学年': '1学年',
          '2学院': '2学院',
          '3专业': '3专业',
          '4班级': '4班级',
          '5学号': '5学号',
          '6姓名': '6姓名',
          '7思想品德': '7思想品德',
          '8体能素质': '8体能素质',
          '9综合评价': '9综合评价',
          '10科学文化素质': '10科学文化素质',
          '11第二课堂': '11第二课堂',
          '12总成绩': '12总成绩',
          '13班级排名': '13班级排名',
          '14专业排名': '14专业排名',
        };

        const arrayWithHeader = [header_zh, ...data];
        console.log(data);
        // let sheet2data = []; // 第二个sheet工作簿
        // 转换sheet格式
        var sheet1 = XLSX.utils.json_to_sheet(arrayWithHeader,
          {
            header: header,
            skipHeader: true
          });
        sheet1["!cols"] = [
          { wch: 15 },
          { wch: 20 },
          { wch: 20 },
          { wch: 25 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 }
        ];

        // 创建一个新的空的workbook      
        var wb = XLSX.utils.book_new();
        // 为每一个工作簿设置名称并添加到workbook（excel表）中
        XLSX.utils.book_append_sheet(wb, sheet1, "综合成绩");
        const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
        // 下载文档并添加文件名称
        openDownloadDialog(workbookBlob, "综合成绩.xlsx");  // 辅助函数openDownloadDialog

      }
    },

    /** 成绩排名列表 */
    getList() {
      this.loading = true;
      listCphScore(this.queryParams).then((response) => {
        this.groupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 升序或者降序
    ascOrDesc() {
      this.queryParams.params.sortType = !Boolean(this.queryParams.params.sortType)
      this.queryParams.params.sortType = Number(this.queryParams.params.sortType)
      this.getList()
      this.isDisabled = true
      setTimeout(() => {
        this.isDisabled = false
      }, 2000)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dormitoryId: null,
        yearId: null,
        rank: null,
        createBy: null,
        updateBy: null,
        status: null,
        number: null,
        createTime: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getScoreDistribution()
    },
    /** 重置按钮操作 */
    resetQuery() {
      let cas = this.$refs.cas;
      cas.inputValue = "";
      this.class_cas = [];
      this.queryParams.classId = null;
      this.queryParams.majorId = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 级联选择数据
    async getCascaderData() {
      const res = await treeStudent()
      this.cascaderData = res.data
      this.cascaderData.forEach(dept => {
        dept.children.forEach(major => {
          major.children.forEach(c => {
            delete c.children
          })
        })
      });
    },
    // 级联选择的项
    handleChange(value) {
      this.queryParams = {
        ...this.queryParams,
        deptId: value[0],
        majorId: value[1],
        classId: value[2],
      }
    },
    // 获取当前查询分数分布情况
    getScoreDistribution() {
      scoreDistribution(this.queryParams).then(response => {
        delete response.data.total
        // 转为数组对象
        this.currentSD = Object.keys(response.data).map(name => ({
          name,
          value: response.data[name]
        }));
        this.createChart()
      })
    },
    // 创建图表
    createChart() {
      this.myChart = echarts.init(this.$refs.scoreCharts);
      this.myChart.setOption({
        title: {
          text: '综合成绩分布情况',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '均值区域',
          type: 'pie',
          radius: '50%',
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: this.currentSD
        }]
      });
    },
    //列出学年信息
    async getStuYear() {
      let res = await listYear();
      this.stu_year_list = [...res.data];
    },
  },
};
</script>
